﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using ResourceBasedAuthApp.Data;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace ResourceBasedAuthApp.Controllers
{
    public class LoginController : ControllerBase
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="userCode"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet("Login")]
        public IActionResult Login([FromQuery] string userCode, string pwd)
        {
            var user = UserRepository.Users.FirstOrDefault(a => a.UserCode == userCode && a.Pwd == pwd);
            if (user == null)
            {
                return NoContent();
            }
            List<Claim> claims = new List<Claim>();
            claims.Add(new Claim(JwtRegisteredClaimNames.Name, user.UserCode));
            claims.Add(new Claim("userName", user.UserName));
            claims.Add(new Claim("userId", user.Id.ToString()));
            claims.Add(new Claim(ClaimTypes.DateOfBirth, user.DateOfBirth.ToString()));

            var secretKey = "qwertyuiop123456";
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
   
            var JwtSecurityToken = new JwtSecurityToken(
                "myToken",
                "aaaa",
                claims,
                expires: DateTime.Now.AddMinutes(24 * 60),
                signingCredentials: credentials
                );
             string token=  new JwtSecurityTokenHandler().WriteToken(JwtSecurityToken);

            return Ok(new { code = 200, message = "success", data = token });
        }
    }
}
